package com.boot;

/**
 * 高并发计数器
 */
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

public class WordCounter {
    private static final ConcurrentHashMap<String, LongAdder> wordCounts = new ConcurrentHashMap<>();

    //线程安全单词计数
    public void countWord(String word) {
        wordCounts.computeIfAbsent(word, k -> new LongAdder()).increment();
    }

    //获取单词计数
    public long getWordCount(String word) {
        return wordCounts.getOrDefault(word, new LongAdder()).longValue();
    }

    public static void main(String[] args) {
        WordCounter counter = new WordCounter();

        //模拟多线程计数
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.countWord("hello");
                counter.countWord("world");

            }
        };

        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(task);
            threads[i].start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        System.out.println("hello：" + counter.getWordCount("hello"));
        System.out.println("world：" + counter.getWordCount("world"));
    }
}
